package com.my.socket.nio.v8;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 * Created by Scarlett on 2018/7/2 0002.
 */
public class ServerReactor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerReactor.class);


    private ServerSocketChannel serverSocketChannel;

    public ServerReactor(String host, int port) throws Exception {
        this.serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel.bind(inetSocketAddress);
        this.serverSocketChannel.configureBlocking(false);
    }

    @Override
    public void run() {
        try {
            new ServerDispatcher(serverSocketChannel, SelectorProvider.provider()).execute();
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        ServerReactor serverReactor = new ServerReactor("127.0.0.1", 9999);
        new Thread(serverReactor).start();
    }
}
